package com.dsk.connector.commons.conf;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TableRegMapping extends TableMapping
{
    private String regExp;

    private Pattern pattern;

    private Pattern targetPattern=Pattern.compile("\\$\\d+");

    private String sourceDb;

    private String targetDb;

    private String targetExpression;

    public String getRegExp() {
        return regExp;
    }

    public void setRegExp(String regExp) {
        this.regExp = regExp;
        this.pattern = Pattern.compile(regExp);
    }

    /**
     * 首先判断是否匹配，如果匹配则返回对应的映射，否则返回null
     * @param sourceTableName 带有.分隔符的表名
     * @return
     */
    public TableRegMapping getMatchMapping(String sourceTableName){
        if(StringUtils.isBlank(sourceTableName)){
            return null;
        }
        if(!sourceTableName.contains(".")){
            return null;
        }
        String[] tableNameArray=sourceTableName.split("\\.");
        TableRegMapping mapping=this.clone();
        mapping.setSourceDb(tableNameArray[0]);
        String tableName=tableNameArray[1];
        Matcher matcher=pattern.matcher(tableName);
        if(!matcher.matches()){
            return null;
        }
        //替换
        Map<String,String> matchValues=new HashMap<>();
        matchValues.put("$0",tableName);
        for(int i=1;i<=matcher.groupCount();i++){
            matchValues.put("$"+i,matcher.group(i));
        }
        String targetTableName=this.targetExpression;
        Matcher targetMatcher=targetPattern.matcher(this.targetExpression);
        while(targetMatcher.find()){
            String replace=targetMatcher.group();
            targetTableName=targetTableName.replace(replace,matchValues.get(replace));
        }
        mapping.setSourceTable(this.sourceDb+"."+tableName);
        mapping.setTargetTable(this.targetDb+"."+targetTableName);

        return mapping;

    }

    public void setSourceDb(String sourceDb) {
        this.sourceDb = sourceDb;
    }

    public void setTargetDb(String targetDb) {
        this.targetDb = targetDb;
    }

    public void setTargetExpression(String targetExpression) {
        this.targetExpression = targetExpression;
    }

    public String getSourceDb() {
        return sourceDb;
    }

    protected TableRegMapping clone() {
        TableRegMapping mapping=new TableRegMapping();
        BeanUtils.copyProperties(this,mapping);
        return mapping;
    }
}
